<template lang="pug">
  .page
    .search-form
      Row(type="flex" justify="start")
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xxl="{span: 6}")
          span.label-txt.w80 订单名称：
          Input(v-model="name" placeholder="请输入订单关键字" clearable)
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xxl="{span: 6}")
          span.label-txt.w80 结算方式：
          Select(v-model="vordertype" placeholder="请选择" clearable)
            Option(v-for="(item, index) of vordertypeArr" :key="index" :value="item.key") {{item.value}}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xxl="{span: 6}")
          span.label-txt.w80 订单状态：
          Select(v-model="orderStatus" placeholder="请选择" clearable)
            Option(v-for="(item, index) of orderStatusArr" :key="index" :value="item.key") {{item.value}}
        Col.pr-20.mb-15(:md="{ span: 12 }" :lg="{ span: 12 }" :xxl="{span: 6}")
          Button(type="info" @click="findBtn") 查询
      ._table.pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(width="100%" stripe :columns="thead" :data="listData"  :loading="loading" @on-selection-change="tableSelectChange")
          ._table_header(slot="header")
            .table-title-lefttxt.pull-left
              span.leftText
                | 订单总数：
                span.text-info.pl-5.pr-5.font-weight {{totalcount}}
                | 条
            .pull-right.table-title-btns
              Button.mr-15(type="info" @click="create") 新建订单
              Button(type="info" @click="closeBtn") 关闭订单
          template(slot-scope="{ row, index }" slot="receiptUserS")
            .ellipsis.un-line(@click="userShow(row.id, row.typeValue, row.createTime)")
              span {{row.receiptUserS}}
          template(slot-scope="{ row, index }" slot="action")
            Button(type="text" size="small" style="margin-right: 5px" @click="checkInfo(row.id)") 详情
            Button(v-if="row.orderStatus === 1" type="text" size="small" @click="dispatch(row.id)") 定向派单
          .clearfix.pl-20.pr-20(slot="footer")
            Page(:total="totalcount" :current="pageIndex" :page-size="pageSize" @on-change="pageChange" show-total)
    Modal(v-model="userStatusModal" title="接单人员状态" width="700")
      Table.beautiful-table( width="100%" stripe :columns="userThead" :data="userList" @on-selection-change="userSelectChange")
        ._table_header(slot="header")
          .pull-left.pl-20.pt-6
            Input(search enter-button placeholder="请输入员工姓名或身份证" style="width:300px" v-model='searchName' @on-search="userShow(currentOrderId,currentOrderTypeValue,currentOrderCreateTime)")
          .pull-right
            //- Button.mr-15(type="info" @click="confirmFinish") 确认完成
        template(slot-scope="{ row, index }" slot="_action")
          Button(type="info" @click="confirmFinish(row.id, row.vOrderId, row.typeValue)" :disabled="+row.detailedStatus !== 4") 确认完成
          //- Button(type="info" @click="confirmFinish(row.id, row.vOrderId)") 确认完成
      .text-center(slot="footer")
        Button(@click="userStatusModal=false") 关闭
    Modal(v-model="finishModal")
      template(v-if="finishOrdertype === 1")
        p(slot="header" style="color:#f60;text-align:center") 请确认完成时间
        .clearfix.mb-10
          span.pull-left.line-h-34.pl-10.pr-10 开始时间：
          DatePicker.pull-left(format="yyyy年MM月dd日" type="date" placeholder="请选择日期" style="width: 150px" :value="startDate" @on-change="handleDatePickerChange('startDate', $event)")
          span.pull-left.line-h-34.pl-10.pr-10 --
          TimePicker.pull-left(format="HH:mm" type="time" placeholder="请选择时间" style="width: 150px" :value="startTime" @on-change="handleTimePickerChange('startTime', $event)")
        .clearfix
          span.pull-left.line-h-34.pl-10.pr-10 结束时间：
          DatePicker.pull-left(format="yyyy年MM月dd日" type="date" placeholder="请选择日期" style="width: 150px" :value="endDate" @on-change="handleDatePickerChange('endDate', $event)")
          span.pull-left.line-h-34.pl-10.pr-10 --
          TimePicker.pull-left(format="HH:mm" type="time" placeholder="请选择时间" style="width: 150px" :value="endTime" @on-change="handleTimePickerChange('endTime', $event)")
        .clearfix.text-center(slot="footer")
          Button(type="info" @click="wXCompleteVOrder('shijian')") 确定
      template(v-else)
        p(slot="header" style="color:#f60;text-align:center") 请输入完成数量
        Input(type="text" v-model="finishNum")
        .clearfix.text-center(slot="footer")
          Button(type="info" @click="wXCompleteVOrder('shuliang')") 确定

    dispatchModal(ref="dispatchModal" :orderId="orderId" @get-list="getListData")
    createModal(ref="createModal" :companyList="companyList" :vordertypeArr="vordertypeArr" :ordercompanyArr="ordercompanyArr" @get-list="getListData")
    checkModal(ref="checkModal" :formValidate="orderInfo" :vordertypeArr="vordertypeArr")
</template>

<script>
import dataApi from '@/api/data.js'
import vOrderApi from '@/api/v_order.api.js'
import dispatchModal from './modal/dispatch.vue'
import createModal from './modal/create.vue'
import checkModal from './modal/check.vue'

export default {
  name: 'v_dispatch',
  components: {
    dispatchModal,
    createModal,
    checkModal
  },
  data () {
    return {
      allWorkers: [], // 所有接单人员
      areaArr: [], // 所有地区
      orderId: '', // 订单id，用于派单
      name: '', // 订单名称
      vordertypeArr: [],
      vordertype: '', // 结算方式
      orderStatusArr: [],
      orderStatus: '1', // 订单状态
      ordercompanyArr: [], // 单位
      finishOrdertype: '', // 确认完成时的订单结算状态
      tabIndex: 0,
      thead: [
        {
          type: 'selection',
          width: 60,
          fixed: 'left'
        },
        {
          title: '发单日期',
          align: 'center',
          key: 'createTime',
          minWidth: 190
        },
        {
          title: '订单类型',
          align: 'center',
          key: 'type',
          minWidth: 100
        },
        {
          title: '订单编号',
          align: 'center',
          key: 'number',
          minWidth: 160
        },
        {
          title: '订单名称',
          align: 'center',
          key: 'orderName',
          minWidth: 150
        },
        {
          title: '所属企业',
          align: 'center',
          key: 'customerName',
          minWidth: 150
        },
        {
          title: '所属门店',
          align: 'center',
          key: 'storeName',
          minWidth: 150
        },
        {
          title: '接单人员',
          align: 'center',
          key: 'receiptUserS',
          minWidth: 150,
          slot: 'receiptUserS'
        },
        {
          title: '订单状态',
          align: 'center',
          key: 'orderStatusName',
          minWidth: 100
        },
        {
          title: '操作',
          align: 'center',
          slot: 'action',
          minWidth: 200
        }
      ],
      listData: [],
      ids: [],
      orderInfo: {}, // 订单详情
      companyList: [], // 公司列表
      userStatusModal: false,
      finishModal: false,
      userThead: [
        // {
        //   type: 'selection',
        //   width: 60
        // },
        {
          title: '姓名',
          key: 'receiptUser',
          minWidth: 150
        },
        {
          title: '身份证号码',
          key: 'idCardNo',
          minWidth: 150
        },
        {
          title: '状态',
          key: 'detailedStatusName',
          minWidth: 150
        },
        {
          title: '操作',
          slot: '_action',
          minWidth: 150
        }
      ],
      userList: [],
      loading: false,
      totalcount: 0,
      pageIndex: 1,
      pageSize: 10,
      userId: '', // 操作人员id
      workerTotalcount: 0,
      workerPageIndex: 1,
      workerPageSize: 10,

      endDate: this.$moment(new Date()).format('YYYY-MM-DD'),
      endTime: this.$moment(new Date()).format('HH:mm'),
      startDate: null,
      startTime: null,
      isFinish: true,
      finishNum: null,
      currentOrderId: null,
      currentOrderDetailId: null,
      currentOrderTypeValue: null,
      currentOrderCreateTime: null,
      searchName: ''
    }
  },
  created () {
    this.getEnum()
    this.getListData()
    this.userId = JSON.parse(localStorage.getItem('clientLoginInfo')).data.userId
  },
  methods: {
    // 获取列表
    getListData () {
      this.ids = []
      this.loading = true
      vOrderApi.getDispatchList({
        Name: this.name,
        Type: this.vordertype,
        OrderStatus: this.orderStatus,
        PageIndex: this.pageIndex,
        PageSize: this.pageSize
      }).then(res => {
        this.loading = false
        if (res.data.success) {
          this.listData = res.data.data
          this.totalcount = res.data.totalRows
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    // 获取详情
    getDetail (id) {
      vOrderApi.getDispatchDetail({
        id: id
      }).then(res => {
        if (res.data.success) {
          this.orderInfo = res.data.data
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    findBtn () {
      this.pageIndex = 1
      this.getListData()
    },
    filterMethod (index) {
      this.tabIndex = index
    },
    tableSelectChange (val) {
      console.log(val)
      this.ids = val.map(item => {
        return item.id
      })
    },
    pageChange (index) {
      this.pageIndex = index
      this.getListData()
    },
    checkInfo (id) {
      this.$refs.checkModal.modalOpen()
      this.getDetail(id)
    },
    dispatch (id) {
      console.log(id)
      this.orderId = id
      this.$refs.dispatchModal.modalOpen()
    },
    create () {
      dataApi.postCustomerList({
        ContractWillBeExpiredMonths: '',
        Name: '',
        CooperateStatus: '',
        CooperateType: '',
        CityId: '',
        ServerId: '',
        PageIndex: '',
        PageSize: '',
        DataSource: 1
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          this.companyList = res.data.data
        } else {
          
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
      this.$refs.createModal.modalOpen()
    },
    closeBtn () {
      if (this.ids.length > 0) {
        vOrderApi.closeDispatch({
          OrderIds: this.ids,
          Userid: this.userId
        }).then(res => {
          if (res.data.success) {
            this.$Message.success(res.data.message)
            this.getListData()
          } else {
            
            this.$Message.error({
              content: res.data.message,
              duration: 10,
              closable: true
            })
          }
        })
      } else {
        this.$Message.warning('请选择需要删除的订单')
      }
    },

    userShow (id, type, createTime) {
      console.log('🌼 id: ', id)
      console.log('🌼 type: ', type)
      console.log('🌼 createTime: ', createTime)
      this.userStatusModal = true
      this.currentOrderId = id
      this.currentOrderTypeValue = type
      this.currentOrderCreateTime = createTime
      this.getOrderWorker(id, type, createTime)
    },

    getOrderWorker (id, type, createTime) {
      this.finishOrdertype = type
      var data = {
        id: id
      }
      if (this.searchName) {
        data.name = this.searchName
      }
      vOrderApi.getOrderWorker(data).then(res => {
        console.log('🌈 res: ', res)
        if (res.data.success) {
          this.userList = res.data.data
          // this.currentOrderId = res.data.data[0].vOrderId
          this.startDate = this.$moment(createTime).format('YYYY-MM-DD')
          this.startTime = this.$moment(createTime).format('HH:mm:ss')
        } else {
          this.userList = []
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },

    userSelectChange (val) {
      console.log(val)
    },
    confirmFinish (id, vOrderId, typeVal) {
      console.log('🍃 id: ', id)
      console.log('🍃 vOrderId: ', vOrderId)
      console.log('🍃 id: ', id)
      this.finishModal = true
      this.currentOrderId = vOrderId
      this.currentOrderDetailId = id
      // this.currentOrderTypeValue = typeVal
    },
    // 订单状态枚举
    getEnum () {
      let groupNames = 'voddjob.orderstatus,voddjob.vordertype,voddjob.ordercompany'
      dataApi.getEnum({
        groupName: groupNames
      }).then(res => {
        this.orderStatusArr = this.getItems(res.data, 'voddjob.orderstatus')
        this.vordertypeArr = this.getItems(res.data, 'voddjob.vordertype')
        this.ordercompanyArr = this.getItems(res.data, 'voddjob.ordercompany')
      })
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },

    // 确认订单
    async wXCompleteVOrder (typeName) {
      var that = this
      var data = {
        OrderId: this.currentOrderId,
        Detailid: this.currentOrderDetailId,
        Userid: this.userId,
        ActualStartTime: this.startDate + ' ' + this.startTime,
        ActualEndTime: this.endDate + ' ' + this.endTime,
        ActualServerNumber: this.finishNum,
        FailureOrder: 0 // 0-完成 1-未完成
      }
      console.log('确认订单data: ', data)
      let res = await vOrderApi.wXCompleteVOrder(data)
      console.log('确认订单res: ', res)
      if (res.status === 200 && res.data.success) {
        this.finishModal = false
        this.$Message.success(res.data.message)
        this.userStatusModal = false
        setTimeout(() => {
          that.pageIndex = 1
          that.getListData()
        }, 1000)
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // DatePicker
    handleDatePickerChange (str, val) {
      console.log('str: ', str)
      console.log('val: ', val)
      this[str] = val
    },

    // TimePicker
    handleTimePickerChange (str, val) {
      console.log('str: ', str)
      console.log('val: ', val)
      this[str] = val
    }
  }
}
</script>

<style lang="less" scoped>
  .style-1{
    color: @main_color;
    cursor: pointer;
    &:hover{
      text-decoration: underline;
    }
  }
  ._table{
    // 表格底部分页样式
    ._table_footer{
      padding: 0 20px;
      margin-top: 15px;
      ._page{
        float: right;
      }
    }
    // 表格头部样式
    ._table_header{
      .leftText{
        display: inline-block;
        padding: 0 5px;
        // margin-right: 20px;
        font-size: 14px;
        line-height: 70px;
      }
    }
  }
  .un-line{
    color: @main_color;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
